/**
 * 文件上传
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yiimanager Software LLC
 */

!function (global, top) {
    "use strict";
    var topLayer = top.layui.layer;
    var topToastr = top.toastr;
    var topYmSpinner = top.ymSpinner;
    var ym2UploadModule = global.angular.module("ym2.upload", []);
    ym2UploadModule.directive("ym2Upload", ["$http", "ym2", "$timeout", function ($http, ym2, $timeout) {
        return {
            restrict: "A",
            template: `<div class="card-body p-0 d-flex flex-wrap" ym2-image-group>
            <div ng-repeat="(index, item) in __fileData" style="{{__fileStyle}}" class="upload-file-container cursor-pointer position-relative mr-1">
                <img ng-if="item.type == 'IMAGE'" class="upload-img" ng-src="{{ item.url }}" alt>
                <video style="{{__fileStyle}}" class="height-auto" ng-if="item.type == 'VIDEO' && videoShow">
                    <source ng-src="{{item.url}}">
                </video>
                <div style="{{__fileStyle}}" class="height-auto" ng-if="item.type == 'AUDIO' || item.type == 'OTHER'">
                    <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
                        <path d="M160 0h512l256 256v704c0 35.3472-28.6528 64-64 64H160c-35.3472 0-64-28.6528-64-64V64c0-35.3472 28.6528-64 64-64z" fill="{{themeColor}}"></path>
                        <path d="M672 0l256 256h-192c-35.3472 0-64-28.6528-64-64V0z" fill="#CAD1F8"></path>
                        <text y="600" x="300" font-size="180px" fill="#fff">{{ item.ext | toUpper }}</text>
                    </svg>
                </div>
                <div class="tool-file-btn text-white">
                    <span ng-click="__deleteUpload(index)" class="bi bi-trash f16" title="清除"></span>
                    <span ng-if="item.type == 'IMAGE'" class="bi bi-eye-fill f16" ym2-full-image srcx="{{ item.url }}" alt="{{ item.link }}" title="查看详情"></span>
                    <span ng-if="item.type != 'IMAGE'" class="bi bi-eye-fill f16" ng-click="openNewWin(item.url)" title="查看详情"></span>
                    <span class="bi bi-cloud-arrow-up-fill f16" ng-click="__clickUpload(index)" title="重新上传"></span>
                </div>
            </div>
            <div ng-hide="hideUploadBtn" ng-click="__clickUpload()" style="{{__fileStyle}}" class="file-add-btn cursor-pointer d-inline-block" title="点击上传"></div>
        </div>`,
            replace: true,
            scope: {},//单独作用域
            require: "ngModel",
            link: function (scope, element, attribute, controller) {
                //定义
                scope.hideUploadBtn = false;
                scope.videoShow = true;
                scope.themeColor = ym2.getAppThemeColor() || "#5bc0de";
                var currentDataIndex;
                var maxNumber = attribute.ym2Max || 1;
                var scenarios = attribute.ym2Upload || null;
                scope.__fileStyle = attribute.ym2Style || "";
                if (scenarios) {
                    scenarios = JSON.parse(scenarios);
                } else {
                    scenarios = [];
                }

                //打开新窗口
                scope.openNewWin = function (url) {
                    global.open(url, '', 'width=800,height=500,toolbar=0,left=500,top=200,location=0,menubar=0');
                };
                //点击上传
                scope.__clickUpload = function (dataIndex) {
                    // layer screen obj
                    var layerScreenObj = ym2.layerScreenOptions("916px");
                    var refererName = ym2.layerRefererWindowName( "self" );

                    // loading flag
                    // var loadingFlag = topYmSpinner.show("加载中...");
                    // iframe 模态框
                    var layerCf = {
                        type: 2, // iframe
                        //skin: 'layui-layer-win10',
                        area: [layerScreenObj.width, "655px"],
                        title: "选择文件",
                        shade: 0.3, // 遮罩透明度
                        shadeClose: false, // 点击遮罩区域，关闭弹层
                        closeBtn: 1,
                        maxmin: false, // 允许全屏最小化
                        anim: 0, // 0-6 的动画形式，-1 不开启
                        scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                        content: ym2.addUrlQueryParam("/__upload/index", {}),
                        success: function(layero, index, that){
                            // topYmSpinner.hide( loadingFlag );
                            // 弹层的最外层元素的 jQuery 对象
                            //console.log(layero);
                            // 弹层的索引值
                            //console.log(index);
                            // 弹层内部原型链中的 this --- 2.8+
                            //console.log(that);
                            // 获取iframe的窗口对象, 添加来源追踪
                            var iframeWin = top[layero.find("iframe")[0]["name"]];
                            iframeWin.__REFERER_WIN_NAME = refererName;
                            if (angular.isNumber(dataIndex)) {
                                currentDataIndex = dataIndex;
                                // 更新
                                iframeWin.onFileSelected = scope.__editFile;
                            } else {
                                // 新增
                                iframeWin.onFileSelected = scope.__addFile;
                            }
                        },
                    };
                    topLayer.open(layerCf);
                };
                //编辑文件
                scope.__editFile = function (data) {
                    var result = controller.$modelValue.concat([]);
                    var item;
                    for (var i = 0; i < data.length; i++) {
                        item = data[i];
                        var type = item.type;
                        if (scenarios.indexOf(type) !== -1) {
                            result[currentDataIndex] = {
                                id: item.id,
                                link: item.link,
                                url: item.url,
                                type: type,
                                ext: item.ext,
                            };
                        }

                        currentDataIndex++;
                    }

                    scope.videoShow = false;
                    if (result.length > maxNumber) {
                        scope.__updateView(result.slice(0, maxNumber));
                    } else {
                        scope.__updateView(result);
                    }

                    // 下一个宏任务渲染
                    $timeout(function () {
                        scope.videoShow = true;
                    });

                    return true;
                };
                //新增文件
                scope.__addFile = function (data) {
                    var result = [];
                    data.forEach(function (value, index) {
                        var type = value.type;
                        if (scenarios.indexOf(type) !== -1) {
                            result.push({
                                id: value.id,
                                link: value.link,
                                url: value.url,
                                type: type,
                                ext: value.ext,
                            });
                        }
                    });
                    if (!result.length) {
                        return false;
                    }
                    var modelValue = controller.$modelValue || [];
                    result = modelValue.concat(result);

                    if (result.length > maxNumber) {
                        scope.__updateView(result.slice(0, maxNumber));
                    } else {
                        scope.__updateView(result);
                    }

                    return true;
                }
                //删除
                scope.__deleteUpload = function (index) {
                    var data = controller.$modelValue.concat([]);
                    data.splice(index, 1);
                    scope.__updateView(data);

                    return true;
                };
                //更新scope
                scope.__updateView = function (data) {
                    data = data || [];
                    controller.$setViewValue(data);
                };
                //监听数据变化
                scope.$watch(function () {
                    return controller.$modelValue;
                }, function (newVal, oldVal) {
                    newVal = newVal || [];
                    scope.hideUploadBtn = newVal.length >= maxNumber;
                    scope.__fileData = newVal;
                }, true);
            }
        };
    }]);
}(window, top);